package com.example.shuiyin.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucketName:shuiyin}")
    private String bucketName;

    @Value("${minio.secure:false}")
    private boolean secure;

    private Map<String, String> buckets; // 多桶配置
    private int connectTimeout;
    private int readTimeout;
    private int writeTimeout;
    private boolean enabled = true;

    /**
     * 获取存储桶名称
     */
    public String getBucket() {
        return this.bucketName;
    }

    /**
     * 获取用途特定的存储桶
     */
    public String getBucketByPurpose(String purpose) {
        if (buckets != null && buckets.containsKey(purpose)) {
            return buckets.get(purpose);
        }
        return bucketName;
    }

    /**
     * 获取用户数据存储桶
     */
    public String getUserBucket() {
        return getBucketByPurpose("user");
    }

    /**
     * 获取水印处理存储桶
     */
    public String getShuiyinBucket() {
        return getBucketByPurpose("shuiyin");
    }

    @Bean
    public MinioClient minioClient() {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            
            // 检查默认存储桶是否存在，不存在则创建
            boolean bucketExists = minioClient.bucketExists(
                    BucketExistsArgs.builder().bucket(bucketName).build());
            if (!bucketExists) {
                minioClient.makeBucket(
                        MakeBucketArgs.builder().bucket(bucketName).build());
                log.info("创建MinIO存储桶: {}", bucketName);
            }
            
            return minioClient;
        } catch (Exception e) {
            log.error("初始化MinIO客户端失败: {}", e.getMessage(), e);
            throw new RuntimeException("初始化MinIO客户端失败", e);
        }
    }
} 